const path = require('path');
const webpack = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const UglifyJsPlugin = require('terser-webpack-plugin');
const HtmlWebpackTagsPlugin = require('html-webpack-tags-plugin');
const CompressionPlugin = require('compression-webpack-plugin');

const isProd = process.env.NODE_ENV === 'production';
module.exports = {
    publicPath: isProd ? '  ./' : '/',
    devServer: {
        open: true,
        proxy: {
            '/icenter/': {
                target: 'http://36.112.11.166:8310/',
                changeOrigin: true,
                pathRewrite: {
                    '^/icenter': '/',
                },
            },
        },
    },
    configureWebpack: config => {
        config.module.unknownContextCritical = false;
        config.resolve.alias = {
            '@': path.resolve(__dirname, 'src'),
            C: path.resolve(__dirname, 'src/components'),
            S: path.resolve(__dirname, 'src/service'),
            U: path.resolve(__dirname, 'src/util'),
        };
        config.entry = isProd
            ? {
                  customSource: './src/CustomSource/CustomSource.js',
                  app: './src/main.js',
              }
            : {
                  Cesium: './ThirdParty/CesiumSource.js',
                  customSource: './src/CustomSource/CustomSource.js',
                  app: './src/main.js',
              };

        config.plugins.push(
            new webpack.DefinePlugin({
                CESIUM_BASE_URL: JSON.stringify('./Cesium/'),
                ICENTER_URL: JSON.stringify('/icenter/'),
                ICENTER_username: JSON.stringify('admin'),
                ICENTER_password: JSON.stringify('icenter'),
                // ICENTER_password: JSON.stringify('admin'),
                // 外网服务
                Y_BASE_URL: JSON.stringify('http://36.112.11.166:8077/product/'),
                CESIUM_NAME: JSON.stringify('Global_Image_JPEG_4326-JPEG-4326'),
                TERRAIN_URL: JSON.stringify('/tilecache/service/terrain/Global_DEM-TERRAIN-4326'),
                PLACE_NAMES: JSON.stringify('Global_ImageLabel-PNG-4326'),
                LEAFLET_NAME: JSON.stringify('Global_VectorMap_White-JPEG-3857'),
            }),
            new CopyWebpackPlugin({
                patterns: [
                    {
                        from: './node_modules/cesium/Build/Cesium',
                        to: 'Cesium',
                    },
                ],
            }),
            new webpack.ProvidePlugin({
                jQuery: 'jquery',
                $: 'jquery',
            })
        );

        if (isProd) {
            config.module.rules.push({
                // 处理jquery
                test: /\.js$/,
                loader: 'thread-loader',
                options: {
                    // worker的数量，默认是cpu核心数
                    workers: 2,
                    // 允许重新生成一个dead work pool,这个过程会降低整体编译速度,开发环境应该设置为false
                    poolRespawn: false,
                },
            });
            // 为生产环境修改配置...
            config.optimization = {
                minimizer: [
                    new UglifyJsPlugin({
                        terserOptions: {
                            warnings: false,
                            compress: {
                                drop_debugger: true,
                                drop_console: true,
                                pure_funcs: ['console.log'],
                            },
                            output: {
                                comments: false,
                            },
                        },
                        sourceMap: false,
                        parallel: true,
                    }),
                ],
                splitChunks: {
                    chunks: 'all',
                    minSize: 300000,
                    maxSize: 10000000,
                    cacheGroups: {
                        vendors: {
                            test: /[\\/]node_modules[\\/]/, // 匹配node_modules目录下的文件
                            priority: -10, // 优先级配置项
                        },
                        default: {
                            minChunks: 2,
                            priority: -20, // 优先级配置项
                            reuseExistingChunk: true,
                        },
                    },
                },
            };
            config.plugins.push(
                new HtmlWebpackPlugin({
                    filename: './index.html',
                    template: './public/index.html',
                }),
                new HtmlWebpackTagsPlugin({
                    append: false,
                    scripts: 'Cesium/Cesium.js',
                }),
                new HtmlWebpackTagsPlugin({
                    append: false,
                    links: 'Cesium/Widgets/widgets.css',
                }),
                // new BundleAnalyzerPlugin(),
                new CompressionPlugin({
                    filename: '[path].gz[query]',
                    algorithm: 'gzip',
                    test: /\.js$|\.css$|\.html$/,
                    threshold: 102400,
                    minRatio: 0.8,
                    deleteOriginalAssets: true,
                })
            );
        } else {
            // 为开发环境修改配置...
            config.devtool = 'eval-source-map';
            config.plugins.push(
                new HtmlWebpackPlugin({
                    filename: './index.html',
                    template: './public/index.html',
                }),
                new HtmlWebpackTagsPlugin({
                    append: false,
                    links: ['./Cesium/Widgets/widgets.css'],
                })
            );
        }
    },
    chainWebpack: config => {
        const oneOfsMap = config.module.rule('scss').oneOfs.store;
        oneOfsMap.forEach(item => {
            item.use('sass-resources-loader')
                .loader('sass-resources-loader')
                .options({
                    resources: './src/style/public.scss',
                })
                .end();
        });
        return config;
    },
};
